//
//  SsehOrderViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "SsehOrderViewController.h"
#import "OrderDetailTableViewCell.h"

#import "OrderDetailsViewController.h"
#import "MJRefresh.h"
#import "OrderInforModel.h"
#import "XRCarouselView.h"
#import "NSString+BRSize.h"
#import "AddMaterialsViewController.h"
#import <TencentLBS/TencentLBS.h>
#import <MapKit/MapKit.h>

#import "SsehMJFooterTool.h"
#import "SsehMJHeaderTool.h"
#import "SsehLocationConverter.h"
#import "NodataView.h"

@interface SsehOrderViewController ()<UITableViewDelegate,UITableViewDataSource,TencentLBSLocationManagerDelegate>

@property (nonatomic,strong) UITableView * ssehTableView;

@property (nonatomic,strong) NSMutableArray * dataSource;

@property (readwrite, nonatomic, strong) TencentLBSLocationManager *locationManager;

@property (nonatomic) CLLocationCoordinate2D userCoordinate;

@property (nonatomic,strong) UISegmentedControl * orderSgc;

@property (nonatomic,strong) NodataView * noDataView;

@end

static int pageIndex = 1;

static NSString * const OrderDetailTableViewCellID = @"OrderDetailTableViewCellID";

static NSString * ssehOrderType = @"";

@implementation SsehOrderViewController{
    
    dispatch_queue_t _queue;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseSetting];
    [self layoutUI];
    [self creatRefreshHeader];
    [self creatRefreshAutoNormalFooter];
}

-(void)baseSetting{
    self.navigationItem.title = @"我的订单";
    _queue = dispatch_queue_create("Sseh", DISPATCH_QUEUE_SERIAL);
    self.navigationController.navigationBar.translucent = NO;
}

-(void)creatRefreshHeader{

    dispatch_sync(_queue, ^{
        self.ssehTableView.mj_header = [SsehMJHeaderTool headerWithRefreshingBlock:^{
            self.orderSgc.userInteractionEnabled = NO;
            pageIndex = 1;
            //请求数据
            NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],@"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],@"page":[NSString stringWithFormat:@"%d",pageIndex],@"order_state":ssehOrderType};
            [[QYNetManager sharedManager]POST:kGetWorkerOrders parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
                [self.ssehTableView.mj_header endRefreshing];
                OrderInforModel * dataModel = [OrderInforModel yy_modelWithDictionary:responseObject];
                [self.dataSource removeAllObjects];
                if (!kArrayIsEmpty(dataModel.data)) {
                    [self.dataSource addObjectsFromArray:dataModel.data];
                    self.ssehTableView.tableHeaderView = nil;
                    
                }else{
                    self.ssehTableView.tableHeaderView = self.noDataView;
                    
                }
                [self.ssehTableView reloadData];
                self.orderSgc.userInteractionEnabled = YES;
            } Failure:^(NSError *error) {
                [self.ssehTableView.mj_header endRefreshing];
                [self showErrorTipWithTitle:SsehPoolNetStr];
                self.orderSgc.userInteractionEnabled = YES;
            }];
            
        }];
        [self.ssehTableView.mj_header beginRefreshing];
    });
    
}

-(void)creatRefreshAutoNormalFooter{
    
    dispatch_sync(_queue, ^{
        self.ssehTableView.mj_footer = [SsehMJFooterTool footerWithRefreshingBlock:^{
            if (kArrayIsEmpty(self.dataSource)) {
                pageIndex = 1;
            }else{
                pageIndex ++;
            }
            
            self.orderSgc.userInteractionEnabled = NO;
            NSDictionary * par = @{@"member_id":DEF_PERSISTENT_GET_OBJECT(SsehUserID),@"member_token":DEF_PERSISTENT_GET_OBJECT(SsehUserToken),@"page":[NSString stringWithFormat:@"%d",pageIndex],@"order_state":ssehOrderType};
            [[QYNetManager sharedManager]POST:kGetWorkerOrders parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
                [self.ssehTableView.mj_footer endRefreshing];
                
                OrderInforModel * dataModel = [OrderInforModel yy_modelWithDictionary:responseObject];
                if (!kArrayIsEmpty(dataModel.data)) {
                    [self.dataSource addObjectsFromArray:dataModel.data];
                    [self.ssehTableView reloadData];
                }
                if (kArrayIsEmpty(self.dataSource)) {
                    self.ssehTableView.tableHeaderView = self.noDataView;
                }else{
                    self.ssehTableView.tableHeaderView = nil;
                }
                self.orderSgc.userInteractionEnabled = YES;
            } Failure:^(NSError *error) {
                [self.ssehTableView.mj_footer endRefreshing];
                [self showErrorTipWithTitle:SsehPoolNetStr];
                self.orderSgc.userInteractionEnabled = YES;
            }];
        }];

    });
    
}

#pragma mark - tableView

-(UITableView *)ssehTableView{

    if (_ssehTableView == nil) {
        self.ssehTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, VIEW_WIDTH, VIEW_HEIGHT-TAB_BAR_HEIGHT-NAVIGATION_BAR_HEIGHT-60) style:UITableViewStylePlain];
        self.ssehTableView.delegate = self;
        self.ssehTableView.dataSource = self;
        self.ssehTableView.backgroundColor = [UIColor backGroudColorForView];
        self.ssehTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.ssehTableView.showsVerticalScrollIndicator = NO;
        self.ssehTableView.showsHorizontalScrollIndicator = NO;
        [self.ssehTableView registerNib:[UINib nibWithNibName:@"OrderDetailTableViewCell" bundle:nil] forCellReuseIdentifier:OrderDetailTableViewCellID];
        [self.view addSubview:self.ssehTableView];

        self.ssehTableView.estimatedRowHeight = 240;

    }
    return _ssehTableView;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    OrderDetailsViewController * vc = [[OrderDetailsViewController alloc]init];
    OrderDetail * model = self.dataSource[indexPath.row];
    vc.orderModel = model;
    [self.navigationController pushViewController:vc animated:YES];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    OrderDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:OrderDetailTableViewCellID];
    if (indexPath.row < self.dataSource.count) {
        OrderDetail * model = self.dataSource[indexPath.row];
        [cell configData:model andSsehOrderType:SsehOrderTypeHomePage andIndexPath:indexPath];
        __weak typeof (self)weakSelf = self;
        cell.leftButtonClick = ^(NSIndexPath *index) {
            [weakSelf refuseWorkerOrderApi:model];
        };
        
        cell.midButtonClick = ^(NSIndexPath *index) {
            
            //导航之前先要获取一下经纬度
            double lat = model.maintailOrderAddressBean.address_latitude.doubleValue;
            double lon = model.maintailOrderAddressBean.address_longitude.doubleValue;
            [weakSelf navigationAlert:CLLocationCoordinate2DMake(lat, lon)];
        };
        
        cell.rightButtonClick = ^(NSIndexPath *index, OrderDetail *orderModel) {
            AddMaterialsViewController * vc = [[AddMaterialsViewController alloc]init];
            vc.orderModel = orderModel;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }

    return cell;

}

#pragma mark - 拒绝订单
-(void)refuseWorkerOrderApi:(OrderDetail *)model{

    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancleOrder:model];
    }];
    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"确认取消该订单？" preferredStyle:UIAlertControllerStyleAlert];
    [aleVC addAction:act1];
    [aleVC addAction:act2];
    [self presentViewController:aleVC animated:YES completion:nil];

}

-(void)cancleOrder:(OrderDetail *)model{

    //member_id    member_token  order_id
    [self showLoading];
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],@"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],@"order_id":model.order_id};
    [[QYNetManager sharedManager]POST:kRefuseWorkerOrder parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            [self showTipWithTitle:@"取消订单成功！"];
            [self creatRefreshHeader];
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];

}

#pragma mark - 导航
-(void)navigationAlert:(CLLocationCoordinate2D)coor{

    UIAlertAction * act1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction * act = [UIAlertAction actionWithTitle:@"用腾讯地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self useQQMap:coor];
    }];
    UIAlertAction * act2 = [UIAlertAction actionWithTitle:@"用自带地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [self iphoneMap:coor];
    }];

    UIAlertAction * act3 = [UIAlertAction actionWithTitle:@"用百度地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self baiduMap:coor];
    }];
    UIAlertAction * act4 = [UIAlertAction actionWithTitle:@"用高德地图导航" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self gaodeMap:coor];
    }];

    UIAlertController * aleVC = [UIAlertController alertControllerWithTitle:nil message:@"请选择导航地图" preferredStyle:UIAlertControllerStyleActionSheet];
    [aleVC addAction:act1];
    [aleVC addAction:act];
    [aleVC addAction:act2];
    [aleVC addAction:act3];
    [aleVC addAction:act4];

    [self presentViewController:aleVC animated:YES completion:nil];

}

-(void)useQQMap:(CLLocationCoordinate2D)coor{
    //coor = CLLocationCoordinate2DMake(31.13184, 121.463718);
    NSString *urlStr;
    if (@available(iOS 9.0, *)) {
        urlStr = [[NSString stringWithFormat:@"qqmap://map/routeplan?from=我的位置type=drive&tocoord=%f,%f&policy=1",coor.latitude,coor.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    } else {
        urlStr = [[NSString stringWithFormat:@"qqmap://map/routeplan?from=我的位置type=drive&tocoord=%f,%f&policy=1",coor.latitude,coor.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    NSURL * r = [NSURL URLWithString:urlStr];
    
    if ([[UIApplication sharedApplication] canOpenURL:r]){
        [[UIApplication sharedApplication] openURL:r];
    }else{
        [self showErrorTipWithTitle:@"未安装腾讯地图"];
    }
}

-(void)iphoneMap:(CLLocationCoordinate2D)coor{

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com"]]){
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coor addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                       MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
    }else{
        [self showErrorTipWithTitle:@"未安装苹果地图"];
    }

}

-(void)baiduMap:(CLLocationCoordinate2D)coor{

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        CLLocationCoordinate2D bdCoor = [SsehLocationConverter wgs84ToBd09:coor];
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/ridenavi?destination=%f,%f&src=ios.baidu.openAPIdemo", bdCoor.latitude, bdCoor.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:url];
    }else{
        [self showErrorTipWithTitle:@"未安装百度地图"];
    }
}

-(void)gaodeMap:(CLLocationCoordinate2D)coor{

    NSURL *scheme = [NSURL URLWithString:@"iosamap://"];
    BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:scheme];
    if (!canOpen) {
        [self showErrorTipWithTitle:@"未安装高德地图"];
        return;
    }

    NSString * urlStr = [NSString stringWithFormat:@"iosamap://navi?sourceApplication=applicationName&poiname=fangheng&poiid=BGVIS&lat=%f1&lon=%f&dev=1&style=2",coor.latitude,coor.longitude];
    NSURL *myLocationScheme = [NSURL URLWithString:urlStr];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:myLocationScheme options:@{} completionHandler:^(BOOL success) {

        }];
    } else {
        [[UIApplication sharedApplication] openURL:myLocationScheme];
    }

}

-(NSMutableArray *)dataSource{

    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataSource;

}


-(TencentLBSLocationManager *)locationManager{
    if (_locationManager == nil) {
        _locationManager = [[TencentLBSLocationManager alloc] init];
        [_locationManager setDelegate:self];
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
        [self.locationManager setRequestLevel:TencentLBSRequestLevelAdminName];
        [_locationManager setApiKey:@"XR6BZ-CQRCP-W7EDB-LPXT7-LTGAS-Z3BE2"];

        CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
        if (authorizationStatus == kCLAuthorizationStatusNotDetermined) {
            [_locationManager requestWhenInUseAuthorization];
        }

    }
    return _locationManager;
}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;

}

-(void)layoutUI{

    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 60)];
    headerView.backgroundColor = [UIColor backGroudColorForView];
    [self.view addSubview:headerView];

    self.orderSgc = [[UISegmentedControl alloc] initWithItems:@[@"全部订单", @"待上门", @"待确认",@"已完成",@"已关闭"]];
    self.orderSgc.tintColor = [UIColor appColor];
    self.orderSgc.backgroundColor = [UIColor whiteColor];
    self.orderSgc.layer.borderColor = [UIColor appColor].CGColor;
    self.orderSgc.layer.borderWidth = 1;
    self.orderSgc.clipsToBounds = YES;
    [self.orderSgc setSelectedSegmentIndex:0];
    CGFloat fontFloat = 14;
    if (HW_DEVICE_IS_IPHONE4S || HW_DEVICE_IS_IPHONE5) {
        fontFloat = 13;
    }else{
        fontFloat = 14;
    }
    [self.orderSgc setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontFloat], NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [self.orderSgc setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontFloat], NSForegroundColorAttributeName:RGBColor(111, 111, 111)} forState:UIControlStateNormal];

    [self.orderSgc addTarget:self action:@selector(orderSgcChangeValue:) forControlEvents:UIControlEventValueChanged];
    self.orderSgc.layer.cornerRadius = 7;
    [headerView addSubview:self.orderSgc];
    [self.orderSgc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.centerX.equalTo(headerView);
        make.width.mas_equalTo(VIEW_WIDTH-20);
    }];

}

-(void)orderSgcChangeValue:(UISegmentedControl *)seg{

    switch (seg.selectedSegmentIndex) {
        case 0:
            ssehOrderType = @"";
            break;
        case 1:
            ssehOrderType = @"2";
            break;
        case 2:
            ssehOrderType = @"3";
            break;
        case 3:
            ssehOrderType = @"5";
            break;
        case 4:
            ssehOrderType = @"0";
            break;

        default:
            break;
    }
    [self.dataSource removeAllObjects];
    [self creatRefreshHeader];
}

-(NodataView *)noDataView{
    
    if (_noDataView == nil) {
        _noDataView = [[NodataView alloc]initWithFrame:CGRectMake(0,60, VIEW_WIDTH, VIEW_HEIGHT-NAVIGATION_BAR_HEIGHT-60-TAB_BAR_HEIGHT)];
        _noDataView.centerImage = [UIImage imageNamed:@"noOrder"];
        _noDataView.titleStr = @"暂无订单";
    }
    return _noDataView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
